import 'package:lib_util/utils/utils.dart';
import 'package:objectbox/objectbox.dart';
import 'package:lib_database/objectbox.g.dart';
import '../basemodel.dart';

@Entity()
class UserSettings {
  @Id()
  int id;
  String uId;
  String? lan;
  String? password;
  bool biometrics; //是否使用生物指纹

  UserSettings({this.id = 0, this.uId = '', this.biometrics = true});

  @override
  String toString() {
    return '{id: $id, uId: $uId,lan: $lan, biometrics: $biometrics, password: $password}';
  }
}

class UserSettingsModel extends BaseModel<UserSettings> {
  UserSettingsModel(Box<UserSettings> box) : super(box);

  bool isPasswordSet(String uId) {
    return Utils.isNotEmpty(getUserSettingsByUId(uId).password);
  }

  List<UserSettings> getAllUserSettings() {
    return box.getAll();
  }

  UserSettings getUserSettings() {
    List<UserSettings> settingsList = box.getAll();
    if (settingsList.isEmpty) {
      UserSettings settings = UserSettings();
      int id = box.put(settings);
      settings.id = id;

      return settings;
    }
    return settingsList.single;
  }

  UserSettings getUserSettingsByUId(String uId) {
    UserSettings? settingsList =
        box.query(UserSettings_.uId.equals(uId)).build().findFirst();
    if (settingsList == null) {
      UserSettings settings = UserSettings();
      settings.uId = uId;
      int id = box.put(settings);
      settings.id = id;

      return settings;
    }
    return settingsList;
  }

  void updateUserSettings(UserSettings settings) {
    box.put(settings, mode: PutMode.update);
  }
}
